package cn.ranko.site.service;

import cn.ranko.bean.easyui.TreeNode;
import cn.ranko.site.mapper.SysMenusMapper;
import cn.ranko.site.model.SysMenus;
import cn.ranko.site.model.SysPermissions;
import cn.ranko.site.model.SysUsers;
import cn.ranko.site.model.SysUsersRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ZJ08 on 2016/8/30.
 */
@Service
public class SysMenusService {

    @Autowired
    SysMenusMapper sysMenusMapper;

    @Autowired
    SysUsersService sysUsersService;

    @Autowired
    SysUsersRolesService sysUsersRolesService;

    /**
     * 根据用户获取用户的菜单
     *
     * @param userId
     * @return
     */
    public List<TreeNode> getMenusByUserId(Long userId) {

        SysUsersRoles sysUsersRoles = sysUsersRolesService.getByUserId(userId);

        List<TreeNode> treeNodes = getTreeNodeByUserIdAndParentId(sysUsersRoles.getRoleId(),-1l);
        return treeNodes;
    }

    private List<TreeNode> getTreeNodeByUserIdAndParentId(Long roleId, long parentId) {
        List<TreeNode> treeNodes = new ArrayList<TreeNode>();
        HashMap params = new HashMap();
        params.put("roleId",roleId);
        params.put("parentId",parentId);
        List<SysMenus> sysMenuses = sysMenusMapper.getMenusByUserIdAndParentId(params);
        if(sysMenuses.size()>0){
            for (int i=0;i<sysMenuses.size();i++){
                TreeNode treeNode = new TreeNode();
                treeNode.setId(sysMenuses.get(i).getId());
                treeNode.setText(sysMenuses.get(i).getMenuname());
                if(sysMenuses.get(i).getLeaf()!=1){
                    //存在子节点的情况下
                    treeNode.setChildren(getTreeNodeByUserIdAndParentId(roleId,sysMenuses.get(i).getId()));
                    treeNode.setState("closed");
                }
                treeNode.setAttributes(sysMenuses.get(i));
                treeNodes.add(treeNode);
            }
        }
        return treeNodes;
    }

    /**
     * 查询所有的节点，用于treegrid进行展示
     * @return
     */
    public List<Map> selectAll() {
        return sysMenusMapper.selectAll();
    }
}
